package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.admin.dto.LoginDto;
import com.heima.article.entity.ApAuthor;
import com.heima.article.feign.ArticleFeign;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.enums.UserEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.catalina.security.SecurityUtil;
import org.apache.commons.lang3.ThreadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2021-12-24
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {


    /**
     * App端登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.参数校验
        if (dto == null || (StringUtils.isBlank(dto.getPhone()) && StringUtils.isBlank(dto.getPassword()) && StringUtils.isBlank(dto.getEquipmentId()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //1.1判断手机号和密码是否为空 ,都不为空,使用手机号和密码进行登录
        if (StringUtils.isNotBlank(dto.getPassword()) && StringUtils.isNotBlank(dto.getPhone())) {
            //2.根据手机号查询用户信息
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUser::getPhone, dto.getPhone());
            ApUser user = this.getOne(queryWrapper);
            if (user == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }

            //2.2 判断用户密码是否正确
            //2.2.1 获取盐,使用用户传入的密码+盐 进行md5计算
            String enterPwdSalt = dto.getPassword() + user.getSalt();
            String enterPwdMd5 = DigestUtils.md5DigestAsHex(enterPwdSalt.getBytes());
            if (!enterPwdMd5.equals(user.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            //2.2.2 用户密码正确，生成jwt令牌
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("userId", user.getId());
            claims.put("userName", user.getName());

            String token = AppJwtUtil.getToken(claims);

            //进行脱敏处理返回结果
            user.setPassword(null);
            user.setPhone(null);
            user.setSalt(null);

            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("user", user);
            resultMap.put("token", token);

            return ResponseResult.okResult(resultMap);
        }
        //3. 用户点击了“先看看”使用设备ID进行登录
        if (StringUtils.isNotBlank(dto.getEquipmentId())) {
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("userId", 0);
            String token = AppJwtUtil.getToken(claims);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            // 通用的响应
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }

    /**
     * 关注和取消关注
     * @param dto
     * @return
     */
    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private ApUserFollowServiceImpl apUserFollowService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Value("${topic.followBehaviorTopic}")
    private String followBehaviorTopic;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //1.从ThreadLocal获取登录的用户信息
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.构建用户关注实体类PO对象
        ApUserFollow apUserFollow = new ApUserFollow();
        //2.1 设置当前登录用户信息
        apUserFollow.setUserId(user.getUserId());
        apUserFollow.setUserName(user.getUserName());

        //2.2 设置关注目标用户信息
        //2.2.1 远程调用文章微服务得到作者信息
        ResponseResult<ApAuthor> responseResult = articleFeign.getAuthorById(dto.getAuthorId());
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApAuthor apAuthor = responseResult.getData();
            apUserFollow.setFollowId(apAuthor.getUserId());
            apUserFollow.setFollowName(apAuthor.getName());
            apUserFollow.setLevel(UserEnum.USER_FOLLOW_LEVEL_ONCE.getVal());

            //3.根据用户操作类型 新增关注记录或者删除关注记录
            LambdaQueryWrapper<ApUserFollow> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUserFollow::getUserId, user.getUserId());
            queryWrapper.eq(ApUserFollow::getFollowId, apAuthor.getUserId());

            //3.1判断是关注用户还是取消关注
            Integer operation = dto.getOperation();

            if (operation.equals(UserEnum.USER_FOLLOW_OPRATION.getVal())) {
                //关注，先查是否已经关注过了，如果没有就新增
                ApUserFollow follow = apUserFollowService.getOne(queryWrapper);
                if (follow == null) {
                    //第一次关注，则新增
                    apUserFollowService.save(apUserFollow);
                }
            }else {
                //取消关注
                apUserFollowService.remove(queryWrapper);
            }
            //4.TODO 发送消息到Kafka中，将来行为微服务作为监听器获取行为数据
            FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
            followBehaviorDto.setUserId(user.getUserId());
            followBehaviorDto.setFollowId(apAuthor.getUserId());
            followBehaviorDto.setEquipmentId(dto.getEquipmentId());
            followBehaviorDto.setOperation(dto.getOperation());

            kafkaTemplate.send(followBehaviorTopic,JSON.toJSONString(followBehaviorDto));
        }
        return ResponseResult.okResult();
        }
}
